﻿#region  文件信息
// ---------------------------------------------------------------------------------------
// <copyright file="HttpHelper.cs" company="">
// 作者：李帅伦
// </copyright>
// <summary>
// 类型简介：
// 类型详细：HttpHelper.cs
// 创建时间：2014-09-13 10:16
// 修改时间：2014-09-13 10:16
// </summary>
// ---------------------------------------------------------------------------------------
#endregion

using System;
using System.Text;
using RestSharp;
using RestSharp.Extensions;

namespace LsTool
{
    /// <summary>
    /// http
    /// </summary>
    public class HttpHelper
    {
      
        /// <summary>
        /// GetPage
        /// </summary> 
        /// <param name="url"></param> 
        /// <param name="method"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static string GetPage(string url, Method method= Method.GET, Action<RestRequest> action = null)
        {
            var client = new RestClient(url);
            var request = new RestRequest(method);
            action?.Invoke(request);
            // execute the request同步
            IRestResponse response = client.Execute(request);
            var content = response.Content; // raw content as string
            return content;
        }

        

        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="url"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static void DownloadData(string url,string path)
        {
            var client = new RestClient(url);
            var request = new RestRequest(Method.GET);
            var downloadData = client.DownloadData(request);
            downloadData.SaveAs(path);
        }

        /// <summary>
        ///      接收从后台POST过来的数据
        /// </summary> 
        /// <param name="stream"></param>
        public static string GetInputStream(System.IO.Stream stream)
        {
            System.IO.Stream s = stream;
            int count = 0;
            byte[] buffer = new byte[1024];
            StringBuilder builder = new StringBuilder();
            while ((count = s.Read(buffer, 0, 1024)) > 0)
            {
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();
            try
            {
                return builder.ToString();
            }
            catch (Exception)
            {
                return null;
            }
        }
    }




}
